!/usr/bin/perl

use strict;
use LWP::UserAgent;
use Crypt::SSLeay;
use JSON;
use HTTP::Cookies;
use HTTP::Status;
use Data::Dumper;

my $browser = LWP::UserAgent->new;
$browser->protocols_allowed( [ 'http', 'https'] );
my $cookieFile = "addama_lwp_cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
    file => $cookieFile,
  );
$cookie_jar->load($cookieFile);
$browser->cookie_jar($cookie_jar);
$browser->timeout(100);
$browser->env_proxy;

if ($#ARGV+1 != 4) {
  die "A file url and output file path are required to run a GET command.  Example usage:\n  perl $0 http://yourhost/addama-rest/myRepo/path/somePath/file1.dat yourPath/file2.dat /yourPath/file1.dat /yourPath/file2.dat\n";
  #exit(0);
}

my ($url, $url2, $fileOut, $fileOut2) = @ARGV;

my $json = new JSON;
my $obj;
getUrl($url);

sub getUrl {
  my ($url) = @_;
  if($url) {
      my $response = $browser->get($url);

      if ($response->is_success) {
          my $myContent = $response->content;
          #print()
          #split url to get file name
          my @url1 = split("/", $url);
          open FILE, ">$url1[-1]" or die $!;
          print FILE $myContent;
          close FILE;
          print "\nFile $url1[-1] saved and closed\n";
          my $response2 = $browser->get($url2);
          if ($response2->is_success) {
             my $myContent2 = $response2->content;
             my @url2 = split("/", $url2);
             open FILE2, ">$url2[-1]" or die $!;
             #open FILE2, ">$fileOut2" or die $!;
             print FILE2 $myContent2;
             close FILE2;
             print "\nFile $url2[-1] saved and closed\n";
          }
      }


      else {
          if($response->code()==401) {
            print "\nLogin is required, please run AddamaLogin.pl and try again.\n\n"
          } else {
            die $response->status_line;
          }
      }
  }
}

